//package crypto; 

import java.io.FileWriter;
import java.io.FileReader;

public class TestMain {
	
	public static char getSinglePad(char cipherChar, char plainText) {
		char pad = 0;
		// guess 1
		pad = (char) (cipherChar - 32 + 64 - plainText);
		if (isPrintableASCII(pad)) {
			return pad;
		}
		// guess 2
		pad = (char) (cipherChar - 32 + 95 + 64 - plainText);
		return pad;
	}
	
	public static boolean isPrintableASCII(char c) {
		if (c >= 32 && c <= 126) {
			return true;
		}
		return false;
	}
	
	public static void main(String[] args) {
		// USAGE:
		// TestMain.java ciphertext_filename plaintext_filename
		// the files must be in local directory
		try {
			if (args[0].trim().equals("") || args[1].trim().equals("")) {
				throw new Exception("incorrect usage");
			}
			String pad;
			FileReader cipherReader = new FileReader(args[0]);
			FileReader plainReader = new FileReader(args[1]);
			FileReader padReader = new FileReader("pad1.txt");
			FileWriter padWriter = new FileWriter("recoveredpad"+ args[1]);
			
			pad = "";
			for (int i = 1; i <= 4000; i++) {
				pad += Character.toString(getSinglePad((char) cipherReader.read(), (char) plainReader.read()));
			}
			
			boolean matchingRecoveredPad = true;
			for (int i = 1; i <= 4000; i++) {
				if (pad.charAt(i) != padReader.read()) {
					matchingRecoveredPad = false;
					break;
				}
			}
			
			padWriter.write(pad);
			padWriter.close();
			cipherReader.close();
			plainReader.close();
			System.out.println("DONE");
		}
		catch (Exception e) {
			System.err.println("ERROR: " + e.getMessage());
		}
	}
	
}
